<template>
  <el-form :model="form"
           ref="form"
           class="edit-report-form"
           :rules="rules"
           @submit.native.prevent
           @keyup.enter.native="onSave"
           v-loading="loading">
    <p>Name your new custom dashboard and select the widgets to be used in the dashboard on the next page.</p>

    <el-form-item prop="name"
                  :label="$t('custom.reports.name')">
      <el-input v-model="form.name"
                maxlength="70"
                :placeholder="$t('custom.reports.name')"></el-input>
    </el-form-item>
    <el-form-item prop="roleIdList"
                  :label="$t('custom.reports.role')">
      <el-select v-model="form.roleIdList"
                 filterable
                 clearable
                 multiple
                 collapse-tags
                 default-first-option
                 style="width:100%"
                 :placeholder="$t('custom.reports.role')">
        <el-option v-for="(item,index) in roleOptions"
                   :key="index"
                   :value="item.roleId"
                   :label="item.name"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="tagList"
                  :label="$t('custom.reports.tag')">
      <el-select v-model="form.tagList"
                 filterable
                 clearable
                 multiple
                 allow-create
                 collapse-tags
                 default-first-option
                 :placeholder="$t('custom.reports.tag')"
                 style="width: 100%;">
        <el-option v-for="(item,index) in tags"
                   :key="index"
                   :label="item.name"
                   :value="item.name">
                   <div style="display: flex;justify-content:space-between;">
                        <ZTooltip :content="item.name"
                           :line="1"
                          placement="top">
                            <span style="flex:1">{{ item.name }}</span>
                        </ZTooltip>
                        <span>
                          <el-button 
                                       style="float: right;font-size: 14px;margin-top: 3px;margin-left: 10px;"
                                       size='mini'
                                       type="text"
                                       @click.stop="deleteTag(item)">
                              <i class="cuifont icon_delete"
                                 style="font-size:14px;color:#CCC"></i>
                            </el-button>
                        </span>
                      </div>


                  </el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="description"
                  :label="$t('custom.reports.description')">
      <el-input v-model="form.description"
                type="textarea"
                :maxlength="500"
                :rows="3"
                @keyup.enter.native.stop
                :placeholder="$t('custom.reports.description')"></el-input>
    </el-form-item>
    <el-form-item prop="theme"
                  v-if="form.layoutType==='report_layout'"
                  :label="$t('custom.reports.theme')">
      <div class="flex" style="width:100%">
        <div :key="index"
             v-for="(item,index) in themeList"
             @click="form.theme=item.label"
             style="position:relative;width:110px;height:80px;marginRight:10px;cursor:pointer"
             :style="{border:form.theme===item.label?'1px solid #45c2b5':''}">
             <el-image
               style="position:absolute;width:20px;height:20px;top:5px;right:5px;z-index:9"
               v-show="form.theme===item.label"
               :src="require('@/assets/img/yes.png')">
             </el-image>
          <el-image
              style="width: 100%; height: 100%; "
              :src="item.url">
          </el-image>
        </div>
      </div>
    </el-form-item>

    <el-form-item class="text-right">
      <el-button type="text"
                 @click="moreEditVisible = true"
                 v-if="$hasPermission('sys:report:moreedit') || $store.state.user.username.includes('mspbots.ai')"
                 size="small">{{ $t('custom.reports.moreedit') }}</el-button>
      <el-button size="small"
                 type="primary"
                 @click="onSave">{{ $t('custom.reports.continue') }}</el-button>
    </el-form-item>

    <el-dialog width="470px"
               :title="$t('custom.reports.moreedit')"
               :visible.sync="moreEditVisible"
               append-to-body
               custom-class="more-dialog"
               destroy-on-close>
      <el-form :model="form"
               v-loading="moreLoading"
               ref="moreForm"
               class="more-edit-dialog-form "
               :rules="rules"
               @submit.native.prevent
               @keyup.enter.native="onSave"
               label-position="top">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item prop="businessType"
                          :label="$t('custom.dataset.businessType')">
              <el-select v-model="form.businessType"
                         :placeholder="$t('custom.dataset.businessType')"
                         style="width: 100%;"
                         :disabled="!$hasPermission('sys:tenant:model:allowtomanagesystemmodel')">
                <el-option v-for="item in businessTypes"
                           :key="item.dictValue"
                           :label="item.dictLabel"
                           :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="status"
                          :label="$t('custom.dataset.status')">
              <el-select v-model="form.status"
                         :placeholder="$t('custom.dataset.status')"
                         style="width: 100%;"
                         :disabled="!$hasPermission('sys:tenant:model:allowtomanagesystemmodel')">
                <el-option v-for="item in statusList"
                           :key="item.dictValue"
                           :label="item.dictLabel"
                           :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="tenantCode"
                          :label="$t('custom.dataset.tenantCode')">
              <SelectClientId v-model="form.tenantCode"
                              :disabled="form.businessType==='Template' || form.businessType==='MSPbots Internal'"
                              :width="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="da"
                          :label="$t('custom.report.da')">
              <el-select v-model="form.da"
                         clearable
                         filterable
                         :placeholder="$t('custom.report.da')"
                         style="width: 100%;">
                <el-option v-for="items in users"
                           :key="items.id"
                           :label="items.realname"
                           :value="items.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="po"
                          :label="$t('custom.report.po')">
              <el-select v-model="form.po"
                         clearable
                         filterable
                         :placeholder="$t('custom.report.po')"
                         style="width: 100%;">
                <el-option v-for="items in users"
                           :key="items.id"
                           :label="items.realname"
                           :value="items.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="jiraNumber"
                          :label="$t('custom.reports.jiraNumber')">
              <el-input v-model="form.jiraNumber"
                        type="text"
                        style="width: 100%"
                        rows="3"
                        :placeholder="$t('custom.reports.jiraNumber')">
                <JiraNumberLink slot="suffix"
                                :jiraNumber="form.jiraNumber" />
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item prop="progress"
                          :label="$t('custom.reports.progress')">
              <el-input v-model="form.progress"
                        :placeholder="$t('custom.reports.progress')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="eta"
                          :label="$t('custom.reports.eta')">
              <el-date-picker v-model="form.eta"
                              type="date"
                              style="width: 100%;"
                              :label="$t('custom.reports.eta')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="priority"
                          :label="$t('custom.reports.priority')">
              <el-select v-model="form.priority"
                         :placeholder="$t('custom.reports.priority')"
                         style="width: 100%;">
                <el-option label="High"
                           value="High"></el-option>
                <el-option label="Medium"
                           value="Medium"></el-option>
                <el-option label="Low"
                           value="Low"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="client"
                          :label="$t('custom.reports.client')">
              <el-input v-model="form.client"
                        type="textarea"
                        rows="2"
                        :placeholder="$t('custom.reports.client')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="uat"
                          :label="$t('custom.reports.uat')">
              <el-select v-model="form.uat"
                         :placeholder="$t('custom.reports.uat')"
                         style="width: 100%;">
                <el-option v-for="item in uatList"
                           :key="item.value"
                           :label="item.lable"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="overheadFilters"
                          :label="$t('custom.reports.overheadFilters')">
              <el-select v-model="form.overheadFilters"
                         :placeholder="$t('custom.reports.overheadFilters')"
                         style="width: 100%;">
                <el-option v-for="item in optionList"
                           :key="item.value"
                           :label="item.lable"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="reportingQa"
                          :label="$t('custom.reports.reportingQa')">
              <el-select v-model="form.reportingQa"
                         :placeholder="$t('custom.reports.reportingQa')"
                         style="width: 100%;">
                <el-option v-for="item in optionList"
                           :key="item.value"
                           :label="item.lable"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="allClientsQa"
                          :label="$t('custom.reports.allClientsQa')">
              <el-select v-model="form.allClientsQa"
                         :placeholder="$t('custom.reports.allClientsQa')"
                         style="width: 100%;">
                <el-option v-for="item in optionList"
                           :key="item.value"
                           :label="item.lable"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="internalNotes"
                          :label="$t('custom.reports.internalNotes')">
              <el-input v-model="form.internalNotes"
                        type="textarea"
                        rows="2"
                        :placeholder="$t('custom.reports.internalNotes')"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template slot="footer">
        <el-button @click="moreEditVisible = false"
                   size="small">{{ $t('Cancel') }}</el-button>
        <el-button type="primary"
                   @click="onSave"
                   size="small">{{ $t('Save') }}</el-button>
      </template>
    </el-dialog>
  </el-form>
</template>

<script>

import { symbolReg } from '@/components/storybook/utilties/reg'
import useErrorMessage from '@/components/storybook/hooks/useErrorMessage'
import { intersectionBy } from 'lodash'
import { optionList, uatList } from '../index.schema'
import JiraNumberLink, { JiraNumberMixin } from '@/components/jira-number-link'
import {
  fetchTag, fetchRole, fetchQuery, fetchAssignRole, fetchReport, updateReport, matchJira, deleteTag
} from '@/api/new'
import ZTooltip from '@/components/storybook/z-tooltip'
import bus from '@/components/storybook/utilties/bus'

export default {
  name: 'EditReportForm',
  components: {
    JiraNumberLink,
    ZTooltip

  },
  mixins: [JiraNumberMixin],
  props: {
    resourceType: [String, Number],
    id: {
      type: String,
      required: true
    },
    selectedRowLayoutType:[String]
  },
  data () {
    const validateSymbol = (rule, value, callback) => {
      if (!symbolReg.test(value)) {
        return callback(new Error(this.$t('validate.isIncludeSymbol')))
      }
      callback()
    }

    return {
      form: {
      },
      rules: {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur', pattern: '[^ \x22]+' },
          { validator: validateSymbol, trigger: 'blur' },
          { min: 0, max: 69, message: this.$t('custom.tips.valueLength', { length: '70' }), trigger: 'change' },
          { validator: this.validateName, trigger: 'blur' }
        ],
        roleIdList: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        description: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          { min: 0, max: 499, message: this.$t('custom.tips.valueLength', { length: '500' }), trigger: 'change' }
        ],
        po: [
         // { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        da: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        jiraNumber: [
         // { required: true, message: this.$t('validate.required'), trigger: 'blur' },
        //  { validator: this.validateJira, trigger: 'blur' }

        ],
        tenantCode: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ]
      },

      loading: false,
      moreLoading: false,
      moreEditVisible: false,
      optionList,
      uatList,
      roles: [],
      tags: [],
      users: [],
      roleOptions: [],
      assignRoles: [],
      businessTypes: [],
      statusList: [],
      themeList:[]
    }
  },
  computed: {
    layoutType () {
       if (this.selectedRowLayoutType&&this.selectedRowLayoutType === 'report_layout_page') {
        return 'report_layout_page'
      }
      if (this.resourceType === 0 || this.resourceType === 100) {
        return 'report_layout'
      }
      if (this.resourceType === 2 || this.resourceType === 120) {
        return 'scorecard_layout'
      }
    }
  },
  created () {
    this.init()
  },
  methods: {
    async init () {
      try {
        this.loading = true
        const [roles, tags, assignRoles, users, businessTypes, statusList, report] = await Promise.all([
          this.getRoles(),
          this.getTags(),
          this.getAssingRoles(),
          this.getUsers(),
          this.getBusinessTypes(),
          this.getStatusList(),
          this.getReport()
        ])
        this.themeList=[]
        const obj=window.SITE_CONFIG['themeList']
        Object.keys(obj).forEach(v=>{
          this.themeList.push({
            label:v,
            url:window.SITE_CONFIG['ossAddressURL']+obj[v].url
          })
        })
        this.roles = roles
        this.tags = tags
        this.users = users
        this.assignRoles = assignRoles
        this.statusList = statusList
        this.businessTypes = businessTypes
        const assigns = this.assignRoles.map(item => ({
          ...item,
          roleId: item.assignId
        }))
        this.roleOptions = intersectionBy(this.roles, assigns, 'roleId')
        const { teamId = '', roleIdList: roleList, ...rest } = report
        const roleIdList = this.roleOptions.filter(({ roleId }) => roleList.includes(roleId)).map(({ roleId }) => roleId)
        this.form = {
          ...rest,
          teamId,
          roleIdList: roleIdList,
          theme:rest.theme||'white'
        }
      } catch (error) {
      } finally {
        this.loading = false
      }
    },
    async getBusinessTypes () {
      const value = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_type_list')
      if (value) {
        const list = value.dataList || []
        if (this.form.businessType === 'MSPbots Internal' && this.$hasPermission('sys:report:type:mspbots internal')) {
          return list.filter(item => item.dictValue === 'MSPbots Internal')
        }

        return list.filter(item => item.dictValue !== 'MSPbots Internal')
      }
      return []
    },
    async getStatusList () {
      const value = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_status_list')
      if (value) {
        const list = value.dataList || []
        if (this.$hasPermission('sys:reports:publishauth')) {
          return list
        }

        return list.filter(item => item.dictValue !== 'Alpha' && item.dictValue !== 'Published')
      }
      return []
    },
    async validateName (rule, value, callback) {
      try {
        const { businessType, tenantCode, layoutType, id } = this.form
        let params = {
          name: value.trim(),
          isNew: false,
          businessType,
          tenantCode,
          layoutType,
          reportId: id
        }
        const { postCheckNameApi } = this.$interface.reports
        const { data: response } = await postCheckNameApi(params)
        if (response.code !== 0) {
          throw new Error('The name is already exists')
        }
        callback()
      } catch (error) {
        callback(error)
      }
    },
    async validateJira (rule, value, callback) {
      try {
        let params = {
          issueIdOrKey: value
        }

        const isMatchJiraNumber = await matchJira(params)
        if (!isMatchJiraNumber) {
          throw new Error(this.$t('custom.component.gadget.checkNumber'))
        }
        callback()
      } catch (error) {
        callback(error)
      }
    },
    async getRoles () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      const { data: response } = await fetchRole(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    async getAssingRoles () {
      const roleIds = (this.$store.state.user.roleList || []).map(({ id }) => id)
      const params = {
        roleId: roleIds
      }
      const { data: response } = await fetchAssignRole(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    async getTags () {
      const params = {
      }
      const { data: response } = await fetchTag(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    deleteTag(tag) {
      if (!tag) return false
      this.$confirm('Are you sure to delete?','warning', {
        type: 'warning',
      })
        .then(async () => {
          const params = {
            id: tag.id,
          }
          const { data: res } = await deleteTag(params)
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.form.tagList = this.form.tagList&&this.form.tagList.filter(
            item => item!== tag.name
          )
          this.tags = await this.getTags()
          this.$message.success(res.msg)
          bus.$emit('update:tags', this.tags)
        })
    },
    async getUsers () {
      const params = {
        datasetKey: 'qwerdsafsadrtfzgsadfggs'
      }
      const { data: response } = await fetchQuery(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    async getReport () {
      const { data: response } = await fetchReport(this.id)
      if (response.code !== 0) {
        throw response.msg
      }
      return response.data || {}
    },

    async onSave () {
      try {
        this.moreEditVisible ? this.moreLoading = true : this.loading = true

        await this.$refs[this.moreEditVisible ? 'moreForm' : 'form'].validate()

        await this.validateForm()

        const { id, ...rest } = this.form
        const params = {
          ...rest,
          reportId: id,
          id,
          layoutType: this.layoutType,
          resourceType: this.resourceType
        }
        const { data: response } = await updateReport(params)
        if (response.code !== 0) {
          throw response.msg
        }
        if (response.data.exist) {
          throw this.$t('custom.dataset.nameexist')
        }
        this.$message.success(response.msg)
        this.$emit('event:success', response.data)
      } catch (error) {
        useErrorMessage(error)
      } finally {
        this.moreEditVisible ? this.moreLoading = false : this.loading = false
      }
    },
    async validateForm () {
      const { da, po, jiraNumber, tenantCode, businessType, description } = this.form
      if (this.$store.state.user.username.includes('mspbots.ai') && this.$hasPermission('sys:report:moreedit')) {
        if (!da) {
          throw this.$t('custom.component.gadget.da')
        }
        if (!po) {
          throw this.$t('custom.component.gadget.po')
        }
        if (tenantCode === '1001' && businessType === 'Custom') {
          // eslint-disable-next-line no-throw-literal
          throw 'The login person is the default tenant, then the type of widget cannot be Custom.'
        }
        if (description.match(/^[ ]*$/)) {
          // eslint-disable-next-line no-throw-literal
          throw 'Description ' + this.$t('validate.required')
        }
        if (jiraNumber !== 'NA') {
          let params = {
            issueIdOrKey: jiraNumber
          }

          const isMatchJiraNumber = await matchJira(params)
          if (!isMatchJiraNumber) {
            throw this.$t('custom.component.gadget.checkNumber')
          }
        }
      }
    }
  }
}
</script>

<style lang="scss">
.more-dialog {
  .el-dialog__body {
    padding: 20px 0 20px 20px;
  }
}
.more-edit-dialog-form {
  height: 400px;
  padding-right: 15px;
  overflow: auto;
  .el-row {
    margin: 0;
  }

  &::-webkit-scrollbar {
    width: 5px;
    height: 5px;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background-color: #17b3a3;
    background-image: -webkit-linear-gradient(
      45deg,
      rgba(255, 255, 255, 0.4) 25%,
      rgba(255, 255, 255, 0.4)
    );
  }

  &::-webkit-scrollbar-track {
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #ededed;
    border-radius: 10px;
  }
}
</style>
